﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lidgren.Network;
using Microsoft.Xna.Framework;
using Lidgren.Network.Xna;
using MobMentality.Social;

namespace MobMentality.Network
{

    class Client
    {
        NetClient client;

        public Client()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("MobMentality");
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);

            client = new NetClient(config);
            client.Start();
        }

        public void DiscoverPeers()
        {
            client.DiscoverLocalPeers(14242);
        }

        public void SendLocation(Vector2 loc)
        {
            NetOutgoingMessage om = client.CreateMessage();
            XNAExtensions.Write(om, loc);
            client.SendMessage(om, NetDeliveryMethod.Unreliable);
        }

        public void SendMessage(String foo)
        {
            //
            // If there's input; send it to server
            //
            NetOutgoingMessage om = client.CreateMessage();
            
            om.Write(foo);
            client.SendMessage(om, NetDeliveryMethod.Unreliable);
        }

        public void ReadMessages()
        {
            // read messages
            NetIncomingMessage msg;
            while ((msg = client.ReadMessage()) != null)
            {
                switch (msg.MessageType)
                {
                    case NetIncomingMessageType.DiscoveryResponse:
                        // just connect to first server discovered
                        client.Connect(msg.SenderEndpoint);
                        break;
                    case NetIncomingMessageType.Data:
                        // server sent a position update
                        //long who = msg.ReadInt64();
                        Vector4 tmp = XNAExtensions.ReadVector4(msg);
                        //int x = msg.ReadInt32();
                        //int y = msg.ReadInt32();
                        //Console.Out.WriteLine(x);
                        //Console.Out.WriteLine(y);
                        Console.WriteLine(tmp);
                        PeopleHolder.Instance.ChangePersonFromVector(tmp);

                        break;
                }
            }
        }

        public void Exit()
        {
            client.Shutdown("bye");
        }
    }

}